//: Playground - noun: a place where people can play

import UIKit

//: # swfit 读书笔记

//: ## 扩展


//: ### 扩展语法
//: 通过关键字 Extensions 为一个已有的类、结构体、枚举类型或者协议类型添加新功能

//: ### 计算型属性
extension Double{
    var km:Double{
        return self * 1_000.0
    }
    
    var m:Double{
        return self
    }
}
let tempMeter = 12.km + 8.m

print("计算型属性\(tempMeter)米")

//: ### 析构器
//: 扩展能为"类"添加新的便利构造器，但是它们不能为类添加新的指定构造器或析构器。指定构造器和析构器必须总是由原始的类实现来提供。
struct Size{
    var w:Double = 0.0 , H:Double = 0.0
}

struct Point{
    var x:Double = 0.0, y:Double = 0.0
}

struct Rect{
    var size:Size = Size ()
    var point:Point = Point ()
}

extension Rect{
    init(center:Point , size:Size) {
       self.init(size: size, point: center)
    }
}

let quickRect = Rect (center: Point (x: 12, y: 12), size: Size (w: 123, H: 123))

class animal{
    var name:String?
}

extension animal{
    //  init() {} 这个直接就报错了
    convenience init(name:String){
        self.init()
        self.name = name
    }
}

//: ### 方法
extension Int{
    
    func extensionPrint(block:()->Void) {
        for _ in 0..<self{
            block()
        }
    }
    
    //: 可变实例方法
    mutating func square() {
        self = self * self
    }
}

2.extensionPrint {
    print("加油你是最胖的")
}

var someInt = 2
someInt.square()
print(" 我原来是-\(2) square 调用后是-\(someInt)")

//: ### 下标
//: 通过下标获取数字的对应数字
extension Int{
    subscript(digitIndex:Int)->Int{
        var decimalBase = 1
        
        for _ in 0..<digitIndex{
            decimalBase *= 10
        }
        return (self/decimalBase)%10
    }
}
print("下标 2 对应的数字是 - \(123456789[2])")

//: ### 嵌套类型

extension Int{
    enum Kind {
        case Nagative,Zero,Positive
    }
    
    var kind:Kind{
        
        switch self {
        case 0:
            return .Zero
        case let x where x > 0:
            return .Positive
        default:
            return .Nagative
        }
    }
}

func printIntergerKinds(_ numbers:[Int]){
    for number in numbers {
        switch number.kind {
        case .Zero:
            print("0", terminator: "")
        case .Positive:
            print("+", terminator: "")
        default:
            print("-", terminator: "")
        }
    }
}

printIntergerKinds([3, 19, -27, 0, -6, 0, 7])
